//
//  HNPatientViewController.m
//  JHFBaseProject
//
//  Created by 朱传正 on 2016/12/29.
//  Copyright © 2016年 好牛. All rights reserved.
//

#import "HNPatientViewController.h"
#import "HNPatientCell.h"
#import "HNPatientNullCell.h"
#import "HNPatientHeadCell.h"
#import "ChatViewController.h"
#import "MainViewController.h"

#define cellHeight @"40"
#define cellChildHeight @"60"
#define cellHeight_zero @"0"

@interface HNPatientViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong)NSMutableArray *dataSource;
@property (nonatomic,strong)NSMutableArray *dataSourceCellHeight;

@property (nonatomic,strong)NSMutableArray *dataSourceFather;
@property (nonatomic,strong)NSMutableArray *dataSourceChild;

@property (nonatomic,assign) NSInteger indexPath_section;

@end

@implementation HNPatientViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"患者";
    _indexPath_section = 0;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


-(void)drawView{
    _dataSource = [NSMutableArray array];
    _dataSourceFather = [NSMutableArray array];
    _dataSourceChild = [NSMutableArray array];
    _dataSourceCellHeight = [NSMutableArray array];
    
    [_tableView setBackgroundColor:[UIColor whiteColor]];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];

    //上拉刷新
    MJRefreshGifHeader *header = [[MJRefreshGifHeader alloc]init];
    [header setRefreshingBlock:^(void){
        //        _page = 1;
        [self getPatientListData];
    }];
    _tableView.mj_header = header;

    [_tableView.mj_header beginRefreshing];
}

#pragma -mark TableView
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSLog(@"%ld",_dataSource.count);
    
    return _dataSource.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return [_dataSourceCellHeight[indexPath.row] integerValue];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSInteger height = [_dataSourceCellHeight[indexPath.row] integerValue];
    
    if (height == [cellHeight integerValue]) {
        static NSString *CellIdentifier = @"HNPatientHeadCell";
  
        HNPatientHeadCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[[NSBundle mainBundle] loadNibNamed:CellIdentifier owner:self options:nil]firstObject];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        NSDictionary *feeRecordDic = _dataSource[indexPath.row];
        NSLog(@"%@",feeRecordDic);
        
        
        NSString *goodsName = [NSString stringWithFormat:@"%@",[feeRecordDic objectForKey:@"goodsName"]];
        cell.cellName.text = goodsName;
        [cell.cellImage setHidden:YES];
//        if (indexPath.row + 1 < _dataSourceCellHeight.count) {
//            NSInteger childHeight = [_dataSourceCellHeight[indexPath.row + 1] integerValue];
//            if (childHeight == [cellHeight_zero integerValue] || childHeight == [cellHeight integerValue] ) {
//                [cell.cellImage setImage:[UIImage imageNamed:@"patient_right.png"]];
//            }else{
//                [cell.cellImage setImage:[UIImage imageNamed:@"patient_bottom.png"]];
//            }
//        }
        if ((indexPath.row ) == _dataSource.count) {
          
        }else{
            if ((indexPath.row + 1)>=_dataSource.count) {
                cell.cellNum.text = [NSString stringWithFormat:@"0"];
            }else{
                NSInteger childHeight = [_dataSourceCellHeight[indexPath.row + 1] integerValue];
                if (childHeight == [cellHeight_zero integerValue]) {
                    int num = 0;
                    for (NSInteger i = indexPath.row + 1 ; i < _dataSource.count; i++) {
                        childHeight = [_dataSourceCellHeight[i] integerValue];
                        if (childHeight == [cellHeight integerValue]) {
                            cell.cellNum.text = [NSString stringWithFormat:@"%d",num];
                            break;
                        }
                        num ++;
                    }
                    
                    cell.cellNum.text = [NSString stringWithFormat:@"%d",num];
                    
                }else if (childHeight == [cellChildHeight integerValue]){
                    int num = 0;
                    for (NSInteger i = indexPath.row +1; i < _dataSource.count; i++) {
                        childHeight = [_dataSourceCellHeight[i] integerValue];
                        if (childHeight == [cellHeight integerValue]) {
                            
                            cell.cellNum.text = [NSString stringWithFormat:@"%d",num];
                            
                            break;
                        }
                        
                        num ++;
                    }
                    
                    
                    cell.cellNum.text = [NSString stringWithFormat:@"%d",num];
                    
                }

            }
        }

     
        return cell;

    }else if(height == [cellChildHeight integerValue]){
        
        static NSString *CellIdentifier = @"HNPatientCell";
        HNPatientCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        
        if (cell == nil) {
            cell = [[[NSBundle mainBundle] loadNibNamed:CellIdentifier owner:self options:nil]firstObject];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        
        NSDictionary *feeRecordDic = _dataSource[indexPath.row];
        
        NSLog(@"%@",feeRecordDic);
        
        NSString *goodsName = [NSString stringWithFormat:@"%@",[feeRecordDic objectForKey:@"buyerUsername"]];
        NSDictionary *peopleInfo = [AppConfig getPeopleInfo:goodsName];
//        NSString *hnNickName = [NSString stringWithFormat:@"%@",[peopleInfo objectForKey:@"hnNickName"]];
        NSString *nickName = [NSString stringWithFormat:@"%@",[peopleInfo objectForKey:@"nickname"]];
        
        
        NSLog(@"qweqweqr----%@",nickName);
        
        
         if (![self isNull:nickName]) {
            cell.cellName.text = nickName;
        }else{
            cell.cellName.text = goodsName;
        }
        NSLog(@"peopleInfo = %@",peopleInfo);
        
        
       
        [cell.cellImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",url_Base,[feeRecordDic objectForKey:@"buyerPhoto"]]] placeholderImage:[UIImage imageNamed:@"detailImage.png"]];
        
        return cell;

    }else{
        static NSString *CellIdentifier = @"HNPatientNullCell";
        HNPatientNullCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        
        if (cell == nil) {
            cell = [[[NSBundle mainBundle] loadNibNamed:CellIdentifier owner:self options:nil]firstObject];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        return cell;
    }
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSInteger height = [_dataSourceCellHeight[indexPath.row] integerValue];
    
    if (height == [cellHeight_zero integerValue]) {
        
    }else if (height == [cellHeight integerValue]){
        if ((indexPath.row + 1)>=_dataSource.count) {
       
        }else{
            NSInteger childHeight = [_dataSourceCellHeight[indexPath.row + 1] integerValue];
            if (childHeight == [cellHeight_zero integerValue]) {
                
                for (NSInteger i = indexPath.row+1; i <=  _dataSource.count; i++) {
                    if (_dataSource.count == i) {
                        [_tableView reloadData];
                        break;
                    }
                    childHeight = [_dataSourceCellHeight[i] integerValue];
                    if (childHeight == [cellHeight integerValue]) {
                          [_tableView reloadData];
                        break;
                    }
                    
                    _dataSourceCellHeight[i] = cellChildHeight;
                    
                }
            }else if (childHeight == [cellChildHeight integerValue]){
                
                for (NSInteger i = indexPath.row + 1 ; i <= _dataSource.count; i++) {
                    if (_dataSource.count == i) {
                        [_tableView reloadData];
                        break;
                    }
                    childHeight = [_dataSourceCellHeight[i] integerValue];
                    if (childHeight == [cellHeight integerValue]) {
                          [_tableView reloadData];
                        break;
                    }
                    
                    _dataSourceCellHeight[i] = cellHeight_zero;
                    
                }
                
            }
        }
        [_tableView reloadData];
        
    }else if (height == [cellChildHeight integerValue]){
        NSDictionary *feeRecordDic = _dataSource[indexPath.row];
        NSString *buyerUsername = [NSString stringWithFormat:@"%@",[feeRecordDic objectForKey:@"buyerUsername"]];
        
        ChatViewController *chatController = [[ChatViewController alloc] initWithConversationChatter:buyerUsername conversationType:EMConversationTypeChat];

        NSDictionary *peopleInfo = [AppConfig getPeopleInfo:buyerUsername];
        NSString *nickName = [NSString stringWithFormat:@"%@",[peopleInfo objectForKey:@"nickname"]];
      
        chatController.patientUsername = buyerUsername;
        if ([AppConfig isNULL:nickName]) {
              chatController.title = buyerUsername;
        }else{
              chatController.title = nickName;
        }
        
        //刷新数据
        dispatch_async(dispatch_get_global_queue(0, 0),^{
            //刷新列表未读数据显示
            [self.tableView reloadData];
            //刷新APP图标未读数据显示
            MainViewController *mainVC = [[MainViewController alloc]init];
            [mainVC setupUnreadMessageCount];
        });
        
        [self.navigationController pushViewController:chatController animated:YES];
        
    }
    
}

#pragma mark - 初始化问题列表消息
-(void)getPatientListData{
    
    NSMutableDictionary *param = [NSMutableDictionary dictionaryWithObjectsAndKeys:static_sessionId,@"sessionId",nil];
    [param setObject:@"1" forKey:@"goodsType"];
    NSLog(@"param = %@",param);
    
    
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager manager] initWithBaseURL:[NSURL URLWithString:url_Base]];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:url_consultlist_mine parameters:param progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSError * error;
        NSLog(@"responseObject = %@",responseObject);
        
        NSDictionary * data=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:&error];
        [self hideHud];
        if (error) {
            NSLog(@"====error1:%@",error);
            [self showHint:@"获取诊金列表失败"];
            NSLog(@"==dict:%@",data);
            return;
        }
        NSLog(@"==dict:%@",data);
        
        NSString * result = [NSString stringWithFormat:@"%@",[data objectForKey:@"result"]];
        if ([result isEqualToString:@"1"]) {
            NSDictionary *obj = [NSDictionary dictionaryWithDictionary:[data objectForKey:@"obj"]];
            
            NSLog(@"----ksadflksdl;gka-----%@",obj);
            
            NSMutableArray *objArr = [NSMutableArray arrayWithObject:[obj objectForKey:@"result"]][0];
            
            [_dataSource removeAllObjects];
            [_dataSourceFather removeAllObjects];
            [_dataSourceChild removeAllObjects];
            [_dataSourceCellHeight removeAllObjects];
//            _dataSourceFather = objArr;
            if (objArr.count > 0) {
                for (int i = 0; i < objArr.count; i++) {
                    [_dataSourceFather addObject:objArr[i]];
                    //                [_dataSourceCellHeight addObject:cellHeight];
                }
            }
         
            NSLog(@"----------dataSourceFather = %@",_dataSourceFather);
            
    
            
            //获取所有服务中的订单
            [self getPatientData];
            
        }else{
            NSString * info = [NSString stringWithFormat:@"%@",[data objectForKey:@"msg"]];
            if ([info isEqualToString:msg_InvalidLoginInformation]) {
                
                [AppConfig removeUserInfo];
                
                [[EMClient sharedClient] logout:YES];
                [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@NO];
                
                HNLoginViewController *loginVC = [[HNLoginViewController alloc]init];
                
                [self.navigationController pushViewController:loginVC animated:YES];
            }
            [self showHint:info];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull  error) {
        NSLog(@"====error:%@",error);
        [self hideHud];
        [self showHint:@"获取诊金列表失败"];
    }];

    
    
    
}

-(void)getPatientData{
    NSMutableDictionary *param = nil;
    
    param = [NSMutableDictionary dictionaryWithObjectsAndKeys:static_sessionId,@"sessionId",nil];
    [param setObject:[EMClient sharedClient].currentUsername forKey:@"sellerUsername"];
//    [param setObject:[EMClient sharedClient].currentUsername forKey:@"buyerUsername"];
    [param setObject:@"11" forKey:@"status"];
    [param setObject:@"1" forKey:@"type"];
    NSLog(@"param = %@",param);
    
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager manager] initWithBaseURL:[NSURL URLWithString:url_Base]];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:url_order_sesrch parameters:param progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSError * error;
        NSDictionary * data=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:&error];
        [self hideHud];
        if (error) {
            NSLog(@"====error1:%@",error);
            [self showHint:@"获取医生列表失败"];
            NSLog(@"==dict:%@",data);
            return;
        }
        NSLog(@"==dict:%@",data);
        
        NSString * result = [NSString stringWithFormat:@"%@",[data objectForKey:@"result"]];
        if ([result isEqualToString:@"1"]) {
            NSMutableArray * obj = [NSMutableArray arrayWithArray:[data objectForKey:@"obj"]];
            NSLog(@"------obj = %@",obj);
            
            if (![AppConfig isNULLObject:obj]) {
                for (NSDictionary *dic in obj) {
                    
                    NSString *nickname = [NSString stringWithFormat:@"%@",[dic objectForKey:@"buyerNickname"]];
                    NSString *photo = [NSString stringWithFormat:@"%@",[dic objectForKey:@"buyerPhoto"]];
                    NSString *hnLoginName = [NSString stringWithFormat:@"%@",[dic objectForKey:@"buyerUsername"]];
                    NSString *orderSn = [NSString stringWithFormat:@"%@",[dic objectForKey:@"orderSn"]];
                    
                    if ([AppConfig isStrNull:nickname] ) {
                        nickname = hnLoginName;
                    }
                    if ([AppConfig isStrNull:photo] ) {
                        photo = @"Icon-40.png";
                    }
                    
                    NSMutableDictionary *peopleUserInfo = [NSMutableDictionary dictionaryWithObjectsAndKeys:hnLoginName,@"hnLoginName" ,nil];
                    [peopleUserInfo setObject:nickname forKey:@"nickname"];
                    [peopleUserInfo setObject:photo forKey:@"photo"];
                    [peopleUserInfo setObject:orderSn forKey:@"orderSn"];
                    NSLog(@"%@",peopleUserInfo);
                    [AppConfig removePeopleInfo:hnLoginName];
                    [AppConfig savePeopleInfo:peopleUserInfo];
                    
                    
                    
                    [_dataSourceChild addObject:dic];
                }

            }
 
            for (int i = 0; i<_dataSourceFather.count; i++) {
                CGFloat fatherMoney = [[NSString stringWithFormat:@"%@",[_dataSourceFather[i] objectForKey:@"shopPrice"]] floatValue];
                [_dataSource addObject:_dataSourceFather[i]];
                [_dataSourceCellHeight addObject:cellHeight];
                if (_dataSourceChild.count > 0) {
                    for (int j = 0;j < _dataSourceChild.count; j ++) {
                        CGFloat childMoney = [[NSString stringWithFormat:@"%@",[_dataSourceChild[j] objectForKey:@"money"]] floatValue];
                        if (fatherMoney == childMoney) {
                            [_dataSource addObject:_dataSourceChild[j]];
                            [_dataSourceCellHeight addObject:cellHeight_zero];
                        }
                    }

                }
                
            }
            
            NSLog(@"-------%@ --------%@",_dataSource,_dataSourceCellHeight);
            
            NSLog(@"%ld  %ld",_dataSource.count,_dataSourceCellHeight.count);
            
            [self.tableView reloadData];
            [self.tableView.mj_header endRefreshing];
            
            
        }else{
              [self.tableView.mj_header endRefreshing];
            NSString * info = [NSString stringWithFormat:@"%@",[data objectForKey:@"msg"]];
            if ([info isEqualToString:msg_InvalidLoginInformation]) {
                
                [AppConfig removeUserInfo];
                
                [[EMClient sharedClient] logout:YES];
                [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@NO];
                
                HNLoginViewController *loginVC = [[HNLoginViewController alloc]init];
                
                [self.navigationController pushViewController:loginVC animated:YES];
            }
            [self showHint:info];
          
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull  error) {
        NSLog(@"====error:%@",error);
        [self hideHud];
        [self showHint:@"获取医生列表失败"];
        [self.tableView.mj_header endRefreshing];

    }];
    

}

//判断是否为空
-(BOOL)isNull:(NSString *)inputStr{
    if (inputStr.length == 0 || [inputStr isEqualToString:@"<null>"]  || [inputStr isEqualToString:@"null"]  || [inputStr isEqualToString:@"(null)"]) {
        return 1;
    }else{
        return 0;
    }
}

@end
